package hub.cathome.controller;

import hub.annotation.Affairs;
import hub.annotation.NotImplementation;
import hub.annotation.View;
import hub.cathome.entity.Page;
import hub.cathome.entity.ResourceLink;
import hub.cathome.entity.ShotBlog;
import hub.cathome.entity.User;
import hub.cathome.entity.tool.ApplicationProperties;
import hub.cathome.service.ProjService;
import hub.cathome.service.ResourceService;
import hub.cathome.service.ShotBlogService;
import hub.cathome.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@SessionAttributes(names = {"shotBlogPage"},types = {Page.class})
public class ShotBlogController {
    @Resource(name="resourceService")
    private ResourceService resourceService;
    @Resource(name="userService")
    private UserService userService;
    @Resource(name="shotBlogService")
    private ShotBlogService shotBlogService;
    @Resource(name="projService")
    private ProjService projService;
    @View("随拍视图")
    @GetMapping("/open/shotBlogs")
    public String ShowTheShotBlogs(@RequestParam(value = "pageNumber",required = false) Integer pageNumber, Model model, HttpSession session){
        Page page = (Page) session.getAttribute("shotBlogPage");

        if(page==null){
            page = new Page();
            page.setPage(1,projService.getProjById(1).getShotBlogPageSize());
            page.setMaxPage((int) Math.ceil(((double)shotBlogService.getShotBlogCount())/page.getPageSize()));
        }else{
            page.setMaxPage((int) Math.ceil(((double)shotBlogService.getShotBlogCount())/page.getPageSize()));
        }
        if(pageNumber==null){
            page.setPageNumber(1);
            pageNumber = 1;
        }else{
            if(pageNumber==-2){
                //上一页
                pageNumber = page.getPageNumber()-1;
            }else if(pageNumber==-1){
                //下一页
                pageNumber = page.getPageNumber()+1;
            }
            while(pageNumber>page.getMaxPage()){
                pageNumber--;
            }
            if(pageNumber<=0){
                pageNumber = 1;
            }
            page.setPageNumber(pageNumber);
        }

        List<ShotBlog> shotBlogList = shotBlogService.getSome(page.getCurrentBegin(),page.getPageSize());
        model.addAttribute("shotBlogList",shotBlogList);
        ArrayList<Integer> pages = new ArrayList<>();
        for(int i = pageNumber,j=0;i<=page.getMaxPage()&&j<5;i++,j++){
            pages.add(i);
        }
        model.addAttribute("pages",pages);
        return "home/index";
    }
    @View("随拍子视图-展示一个随拍")
    @GetMapping("/open/shotBlog/{shotBlogId}")
    public String ShowShotGalleryBlog(@PathVariable int shotBlogId,Model model){
        ShotBlog shotBlog = shotBlogService.getShotBlogById(shotBlogId);
        model.addAttribute("shotBlog",shotBlog);
        User u = userService.getUserByUserId(shotBlog.getUserId());
        u.setPassword(11L);
        model.addAttribute("shotBlogAuthor",u);
        shotBlog.setLikeCount(shotBlog.getLikes().size());
        shotBlog.setCommentCount(shotBlog.getComments().size());
        return "open/shotBlog";
    }
    @View("编辑随拍")
    @RequestMapping("/home/shotBlog/edit/{shotBlogId}")
    public String editShotBlog(@PathVariable int shotBlogId,Model model){
        ShotBlog shotBlog = shotBlogService.getShotBlogById(shotBlogId);
        model.addAttribute("shotBlog",shotBlog);
        return "home/shotBlog/edit";
    }
    @Deprecated
    private boolean tryGetShotBlog(@PathVariable String shotBlogId, Model model) {
        int id;
        try{
            id = Integer.parseInt(shotBlogId);
        }catch (Exception e){
            model.addAttribute("error",e.toString());
            return true;
        }
        ShotBlog shotBlog = shotBlogService.getShotBlogById(id);
        model.addAttribute("shotBlog",shotBlog);
        return false;
    }

    @Affairs("删除随拍")
    @RequestMapping("/affair/shotBlog/delete/{shotBlogId}")
    public String deleteShotBlog(@PathVariable String shotBlogId,Model model){
        int id;
        try{
            id = Integer.parseInt(shotBlogId);
        }catch (Exception e){
            model.addAttribute("error",e.toString());
            return "error/error";
        }
        shotBlogService.deleteShotBlog(id);
        return "redirect:/home";
    }
    @Affairs("发布随拍")
    @GetMapping("/open/shotBlog/add")
    public String newShotBlogView(){
        return "home/shotBlog/add";
    }
    @NotImplementation("未实现接收数据并存储")
    @Affairs("发布随拍")
    @RequestMapping("/affair/shotBlog/add")
    public String publishShotBlog(@RequestParam("image") MultipartFile file, @RequestParam("content") String content, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        ShotBlog shotBlog = new ShotBlog();
        shotBlog.setContent(content);
        shotBlog.setDate(new Date());
        shotBlog.setUserId(user.getId());
        shotBlogService.insertShotBlog(shotBlog);
        String fileName = file.getOriginalFilename();
        String extName = StringUtils.getFilenameExtension(fileName);
        String targetName = UUID.randomUUID()+"."+extName;
        ResourceLink resourceLink = new ResourceLink();
        resourceLink.setDate(new Date());
        resourceLink.setPath(targetName);
        resourceLink.setType(1);
        resourceLink.setForId(shotBlog.getBlogId());
        resourceService.insertResourceLink(resourceLink);
        String absoluteLocalPath = ApplicationProperties.getAbsoluteLocalPath(targetName);
        String prePath = absoluteLocalPath.substring(0,absoluteLocalPath.lastIndexOf(File.separator));
        if(!new File(prePath).exists()){
            boolean success = new File(prePath).mkdirs();
            if(!success){
                return "error/error";
            }
        }
        try {
            file.transferTo(new File(absoluteLocalPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/home";
    }
    @Affairs("保存更改")
    @RequestMapping("/affair/shotBlog/update/{shotBlogId}")
    public String saveShotBlog(@RequestParam("image") MultipartFile file ,@RequestParam("content") String content,@PathVariable Integer shotBlogId){
        List<ResourceLink> resourceLinks = resourceService.getShotBlogResourceLinkByShotBlogId(shotBlogId);
        ShotBlog shotBlog = shotBlogService.getShotBlogById(shotBlogId);
        shotBlog.setContent(content);
        for(ResourceLink resourceLink : resourceLinks){
            resourceService.deleteResourceLink(resourceLink.getResourceId());
        }
        String fileName = file.getOriginalFilename();
        String extName = StringUtils.getFilenameExtension(fileName);
        String targetName = UUID.randomUUID()+"."+extName;
        ResourceLink resourceLink = new ResourceLink();
        resourceLink.setDate(new Date());
        resourceLink.setPath(targetName);
        resourceLink.setType(1);
        resourceLink.setForId(shotBlog.getBlogId());
        resourceService.insertResourceLink(resourceLink);
        shotBlogService.updateShotBlog(shotBlog);
        String absoluteLocalPath = ApplicationProperties.getAbsoluteLocalPath(targetName);
        String prePath = absoluteLocalPath.substring(0,absoluteLocalPath.lastIndexOf(File.separator));
        if(!new File(prePath).exists()){
            boolean success = new File(prePath).mkdirs();
            if(!success){
                return "error/error";
            }
        }
        try {
            file.transferTo(new File(absoluteLocalPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/open/shotBlog/"+shotBlogId;
    }
}
